<template>
  <div class="hanzi-generation-container">
    <el-card class="generation-card">
      <template #header>
        <div class="card-header">
          <span>汉字生成</span>
        </div>
      </template>
      
      <el-form :model="generationForm" ref="generationFormRef" :rules="rules" label-width="80px">
        <el-form-item label="汉字" prop="char">
          <el-input v-model="generationForm.char" placeholder="请输入要生成的汉字" maxlength="1" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="步数" prop="steps">
          <el-slider v-model="generationForm.steps" :min="1" :max="100" :step="1" show-stops show-input></el-slider>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="loading">生成汉字</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div v-if="generationResult" class="result-container">
        <h3>生成结果</h3>
        <div class="result-info">
          <p>状态: 
            <el-tag :type="statusTypeMap[generationResult.status]">{{ statusTextMap[generationResult.status] }}</el-tag>
          </p>
          <p>请求ID: {{ generationResult.requestId || '-' }}</p>
          <p>创建时间: {{ formatDateTime(generationResult.createTime) }}</p>
          <p v-if="generationResult.generationTime">生成耗时: {{ (generationResult.generationTime / 1000).toFixed(2) }}s</p>
          <p>错误信息: {{ generationResult.errorMessage || '-' }}</p>
        </div>
        <div v-if="generationResult.ossUrl" class="image-container">
          <el-image 
            :src="generationResult.ossUrl" 
            alt="生成的汉字图像" 
            :preview-src-list="[generationResult.ossUrl]"
            fit="contain"
            class="result-image"
          ></el-image>
        </div>
      </div>
    </el-card>

    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <span>历史记录</span>
          <div class="search-container">
            <el-input 
              v-model="searchChar" 
              placeholder="输入汉字查询" 
              clearable 
              maxlength="1" 
              @keyup.enter="searchByChar"
              @clear="loadRecords"
            >
              <template #append>
                <el-button :icon="Search" @click="searchByChar"></el-button>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table :data="recordsList" style="width: 100%" v-loading="tableLoading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="requestId" label="请求ID" width="120">
          <template #default="scope">
            {{ scope.row.requestId || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="chineseChar" label="汉字" width="80"></el-table-column>
        <el-table-column prop="steps" label="步数" width="80"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="statusTypeMap[scope.row.status]">{{ statusTextMap[scope.row.status] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="generationTime" label="生成时间(s)" width="120">
          <template #default="scope">
            {{ scope.row.generationTime ? (scope.row.generationTime / 1000).toFixed(2) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="errorMessage" label="错误信息" width="150">
          <template #default="scope">
            <el-tooltip v-if="scope.row.errorMessage" :content="scope.row.errorMessage" placement="top" effect="light">
              <span class="error-text">{{ truncateText(scope.row.errorMessage, 15) }}</span>
            </el-tooltip>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="图像" min-width="150">
          <template #default="scope">
            <el-image 
              v-if="scope.row.ossUrl" 
              :src="scope.row.ossUrl" 
              :preview-src-list="[scope.row.ossUrl]"
              fit="contain"
              class="table-hanzi-image"
            ></el-image>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <el-card class="stats-card" v-if="stats">
      <template #header>
        <div class="card-header">
          <span>统计信息</span>
          <el-button :icon="Refresh" circle @click="loadStats"></el-button>
        </div>
      </template>
      
      <div class="stats-container">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <h3>总记录数</h3>
              <p>{{ stats.totalRecords }}</p>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item success">
              <h3>成功记录</h3>
              <p>{{ stats.successRecords }}</p>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item processing">
              <h3>处理中</h3>
              <p>{{ stats.processingRecords }}</p>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item failed">
              <h3>失败记录</h3>
              <p>{{ stats.failedRecords }}</p>
            </div>
          </el-col>
        </el-row>
        <div class="success-rate">
          <h3>成功率</h3>
          <el-progress :percentage="parseFloat(stats.successRate)" :format="percentFormat"></el-progress>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { 
  generateHanzi, 
  getRecordsByChar, 
  getRecordsByPage, 
  getHanziStats,
  type ApiResponse,
  type HanziGenerationRequest,
  type HanziGenerationResponse,
  type StatsResponse,
  type PageResponse
} from '@/api/hanzi'

// 表单数据
const generationForm = reactive<HanziGenerationRequest>({
  char: '',
  steps: 50
})

// 表单验证规则
const rules = {
  char: [
    { required: true, message: '请输入汉字', trigger: 'blur' },
    { 
      validator: (rule: any, value: string, callback: any) => {
        if (!/^[\u4e00-\u9fa5]$/.test(value)) {
          callback(new Error('请输入一个有效的汉字'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur'
    }
  ],
  steps: [
    { required: true, message: '请选择步数', trigger: 'change' },
    { type: 'number', min: 1, max: 100, message: '步数必须在1到100之间', trigger: 'change' }
  ]
}

// 引用
const generationFormRef = ref<any>(null)
const loading = ref<boolean>(false)
const tableLoading = ref<boolean>(false)
const generationResult = ref<HanziGenerationResponse | null>(null)
const recordsList = ref<HanziGenerationResponse[]>([])
const searchChar = ref<string>('')
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const total = ref<number>(0)
const stats = ref<StatsResponse | null>(null)

// 状态映射
const statusTypeMap: Record<string, string> = {
  'processing': 'warning',
  'success': 'success',
  'failed': 'danger'
}

const statusTextMap: Record<string, string> = {
  'processing': '处理中',
  'success': '成功',
  'failed': '失败'
}

// 方法
function submitForm() {
  generationFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true
      try {
        const response = await generateHanzi(generationForm)
        if (response.code === 200) {
          generationResult.value = response.data
          ElMessage({
            type: 'success',
            message: '汉字生成请求已提交'
          })
          
          // 如果生成成功，刷新列表和统计信息
          loadRecords()
          loadStats()
          
          // 如果处理中，设置轮询检查状态
          if (response.data.status === 'processing') {
            pollGenerationStatus(response.data.id)
          }
        } else {
          ElMessage.error(response.msg || '汉字生成请求失败')
        }
      } catch (error) {
        console.error('汉字生成错误:', error)
        ElMessage.error('汉字生成请求失败')
      } finally {
        loading.value = false
      }
    }
  })
}

function resetForm() {
  generationFormRef.value.resetFields()
  generationForm.steps = 50
  generationResult.value = null
}

function pollGenerationStatus(id: number) {
  // 由于没有直接获取单个记录的API，这里使用汉字查询
  // 在实际使用中，可以添加根据ID查询的API
  const timer = setInterval(async () => {
    try {
      const response = await getRecordsByChar(generationForm.char)
      if (response.code === 200 && response.data.list) {
        const record = response.data.list.find((item: HanziGenerationResponse) => item.id === id)
        
        if (record && record.status !== 'processing') {
          generationResult.value = record
          clearInterval(timer)
          
          // 通知用户生成完成
          ElNotification({
            title: '汉字生成完成',
            message: record.status === 'success' ? '汉字已成功生成' : '汉字生成失败',
            type: record.status === 'success' ? 'success' : 'error'
          })
          
          // 刷新列表和统计
          loadRecords()
          loadStats()
        }
      } else {
        clearInterval(timer)
      }
    } catch (error) {
      console.error('轮询状态错误:', error)
      clearInterval(timer)
    }
  }, 5000) // 每5秒检查一次
}

// 加载分页记录
async function loadRecords() {
  tableLoading.value = true
  try {
    const response = await getRecordsByPage(currentPage.value, pageSize.value)
    if (response.code === 200) {
      recordsList.value = response.data.list
      total.value = response.data.total
    } else {
      ElMessage.error(response.msg || '加载记录失败')
    }
  } catch (error) {
    console.error('加载记录错误:', error)
    ElMessage.error('加载记录失败')
  } finally {
    tableLoading.value = false
  }
}

// 根据汉字查询记录
async function searchByChar() {
  if (!searchChar.value) {
    loadRecords()
    return
  }
  
  tableLoading.value = true
  try {
    const response = await getRecordsByChar(searchChar.value)
    if (response.code === 200 && response.data.list) {
      recordsList.value = response.data.list
      total.value = recordsList.value.length
    } else {
      ElMessage.error(response.msg || '查询记录失败')
    }
  } catch (error) {
    console.error('查询记录错误:', error)
    ElMessage.error('查询记录失败')
  } finally {
    tableLoading.value = false
  }
}

// 加载统计信息
async function loadStats() {
  try {
    const response = await getHanziStats()
    if (response.code === 200) {
      stats.value = response.data
    }
  } catch (error) {
    console.error('加载统计信息错误:', error)
  }
}

// 分页处理
function handleSizeChange(size: number) {
  pageSize.value = size
  loadRecords()
}

function handleCurrentChange(page: number) {
  currentPage.value = page
  loadRecords()
}

// 格式化日期时间
function formatDateTime(timestamp: string | null) {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`
}

function padZero(num: number) {
  return num.toString().padStart(2, '0')
}

// 百分比格式化
function percentFormat(val: number) {
  return val + '%'
}

// 辅助函数：截断文本
function truncateText(text: string | null, maxLength: number): string {
  if (!text) return '-';
  return text.length > maxLength ? text.substring(0, maxLength) + '...' : text;
}

// 生命周期钩子
onMounted(() => {
  loadRecords()
  loadStats()
})
</script>

<style scoped>
.hanzi-generation-container {
  padding: 20px;
}

.generation-card, .history-card, .stats-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-container {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.result-info {
  margin-bottom: 15px;
}

.image-container {
  display: flex;
  justify-content: center;
  margin: 15px 0;
}

.result-image {
  max-width: 100%;
  max-height: 300px;
  width: 200px;
  height: 200px;
  object-fit: contain;
  background-color: #f8f8f8;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}

.error-message {
  color: #f56c6c;
}

.search-container {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.stats-container {
  padding: 10px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  border-radius: 4px;
  background-color: #f5f7fa;
}

.stat-item h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #606266;
}

.stat-item p {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
}

.success {
  background-color: #f0f9eb;
}

.processing {
  background-color: #fdf6ec;
}

.failed {
  background-color: #fef0f0;
}

.success-rate {
  margin-top: 20px;
}

.success-rate h3 {
  margin-bottom: 10px;
  font-size: 16px;
  color: #606266;
}

.error-text {
  color: #F56C6C;
  cursor: pointer;
  text-decoration: underline;
  text-decoration-style: dotted;
}

.table-hanzi-image {
  width: 60px;
  height: 60px;
  object-fit: contain;
  background-color: #f8f8f8;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
}
</style> 